package znbkTestPaperRdqh.guide;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.text.Html;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.BaseExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.lancooznbk.MyApplication;
import com.example.lancooznbk.R;
import com.example.lancooznbk.view.base.BaseActivity;
import com.example.lancooznbk.view.base.BaseFragment;
import com.example.lancooznbk.view.base.ILoadPaperView;
import com.example.lancooznbk.view.widget.LoadingDialog;
import com.example.lancooznbk.view.widget.ScaleButton;
import com.lancoo.dictionary.activity.DictionaryActicity;
import com.lancoo.reviewsystem.utils.ToastUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import lancooControl.AndroidBug5497Workaround;
import znbkListRdqh.entity.WeekAscensionListEntity;
import znbkTestPaperInfor.ZnbkPaperDef;
import znbkTestPaperRdqh.ZnbkPaperRdqhInfor;
import znbkTestPaperRdqh.activity.WeekAscensionPaperActivity;
import znbkTestPaperRdqh.entity.WeekAscensionPaperEntity;
import znbkTestPaperRdqh.presenter.WeekAscensionPaperPresenter;

/**
 * Created by Administrator on 2018\4\11 0011.
 */

public class ReviewPaperGuideActivity extends BaseActivity implements ILoadPaperView<WeekAscensionPaperEntity> {

    private WeekAscensionPaperPresenter mPresenter;
    private WeekAscensionPaperEntity mEntityRdqh;

    private ScaleButton mSBtnClose;//标题栏关闭按钮
    private TextView mTvReviewTitle;//标题栏文字
    private TextView mTvCommonlyTestPoint;//一般考点
    private TextView mTvWeekPoint;//薄弱点
    private TextView mTvTestPoint;//考点
    private ExpandableListView mELvTestPoint;//考点轴
    private ScaleButton mSbtnIntoReview;//进入学习
    private List<String> group=new ArrayList<String>();
    private List<List<String>> child=new ArrayList<List<String>>();
    private ExpandableAdapter adapter;

    public int mQuesOrPaperFrom;
    private WeekAscensionListEntity.ModelPaperInfoListBean mEntity;
    public static final  String PAPER_ENTITY = "paperEntity";
    public static final String PAPER_FROM = "paperFrom";

    public  static void launch(BaseFragment mContext, WeekAscensionListEntity.ModelPaperInfoListBean entity, @ZnbkPaperDef.PaperFrom int quesOrPaperFrom){
        ZnbkPaperRdqhInfor.PaperId = entity.getPaperID();
        Bundle bundle = new Bundle();
        bundle.putSerializable(PAPER_ENTITY,entity);
        bundle.putInt(PAPER_FROM,quesOrPaperFrom);
        Intent intent = new Intent(mContext.getContext(), ReviewPaperGuideActivity.class);
        intent.putExtras(bundle);
        mContext.startActivityForResult(intent,1);

    }

    @Override
    public int attachLayoutRes() {
        return R.layout.znbk_review_paper_guide;
    }

    @Override
    protected void initViews() {

        MyApplication.addDestoryActivity(ReviewPaperGuideActivity.this,"1");

        AndroidBug5497Workaround.assistActivity(this);
        mPresenter = new WeekAscensionPaperPresenter(this,ZnbkPaperDef.FROM_WEEK_ASCENSION_GUIDE);
        Bundle bundle = getIntent().getExtras();
        if (bundle != null){
            mEntity = (WeekAscensionListEntity.ModelPaperInfoListBean) bundle.getSerializable(PAPER_ENTITY);
            mQuesOrPaperFrom = bundle.getInt(PAPER_FROM);
        }
        //核心代码.
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }
        RelativeLayout relToolbar = (RelativeLayout) findViewById(R.id.rlayout_back);
        int statusBarHeight = getStatusBarHeight();
        LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) relToolbar.getLayoutParams();
        layoutParams.setMargins(0,statusBarHeight,0,0);

        mSBtnClose = (ScaleButton) findViewById(R.id.sbtn_close);
        mSBtnClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        mTvReviewTitle = (TextView) findViewById(R.id.tv_reviewTitle);

        mTvCommonlyTestPoint = (TextView) findViewById(R.id.tv_commonlyTestPoint);

        mTvWeekPoint = (TextView) findViewById(R.id.tv_weekPoint);

        mTvTestPoint = (TextView) findViewById(R.id.tv_testPoint);

        mELvTestPoint = (ExpandableListView) findViewById(R.id.elv_testPoint);

        mSbtnIntoReview = (ScaleButton) findViewById(R.id.sbtn_intoReview);
        mSbtnIntoReview.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //进入弱点强化卷
                if(mEntityRdqh!=null){
                    WeekAscensionPaperActivity.launch(ReviewPaperGuideActivity.this, ZnbkPaperRdqhInfor.ModelPaperInfoListBean, ZnbkPaperDef.FROM_WEEK_ASCENSION);
                }
            }
        });

    }

    @Override
    protected void updateViews(boolean isRefresh) {
        mPresenter.getData(isRefresh);
    }

    @Override
    public void loadPaperData(WeekAscensionPaperEntity data) {
        mEntityRdqh = data;

        /*
        * 显示标题栏信息：PaperName
        * */
        String PaperName = mEntityRdqh.getModelSinglePaperInfo().getModelPaperInfo().getPaperName();
        mTvReviewTitle.setText(Html.fromHtml(PaperName));

        /*
        * 显示引导页进入页面按钮：1.开始学习2.继续学习3.进入自评4.查看详情
        * */
        mSbtnIntoReview.setText("开始学习");

        /*
        * 计算一般考点的数量
        * */

        ArrayList<String> AllArrayCommonlyTestPoint = new ArrayList<>();
        int PaperQuesCount = mEntityRdqh.getModelSinglePaperInfo().getModelTKQueList().size();
        for(int i=0;i<PaperQuesCount;i++){
            int QuesImportantZSDCount = mEntityRdqh.getModelSinglePaperInfo().getModelTKQueList().get(i).getImportantZSD().size();
            for(int j=0;j<QuesImportantZSDCount;j++){
                String ZSDName =  mEntityRdqh.getModelSinglePaperInfo().getModelTKQueList().get(i).getImportantZSD().get(j).getZSDName();
                AllArrayCommonlyTestPoint.add(ZSDName);
            }
        }

        Log.e("","");
        Set<String> strSet = new HashSet<String>(AllArrayCommonlyTestPoint);
        String[] temp = new String[strSet.size()];
        Iterator<String> ite = strSet.iterator();
        for(int i = 0;ite.hasNext();i++){
            temp[i] = ite.next();
        }

        List<String> ArrayCommonlyTestPoint = Arrays.asList(temp);
        int WeekPointCount = mEntityRdqh.getModelSinglePaperInfo().getModelPaperInfo().getKnowledgeList().size();
        for(int i=0;i<WeekPointCount;i++){
            String KnowledgeName = mEntityRdqh.getModelSinglePaperInfo().getModelPaperInfo().getKnowledgeList().get(i).getKnowledgeName();
            if(ArrayCommonlyTestPoint.contains(KnowledgeName)){
                ArrayList<String> arrayList = new ArrayList<String>(ArrayCommonlyTestPoint);
                arrayList.remove(KnowledgeName);
                ArrayCommonlyTestPoint = arrayList;
            }
        }


        int CommonlyTestPointCount = ArrayCommonlyTestPoint.size();
        mTvCommonlyTestPoint.setText(String.valueOf(CommonlyTestPointCount));

        /*
        * 获取基础得分集合：ArrayBasicScore
        * 获取达标得分集合：ArrayAvalidScore
        * 获取薄弱知识点集合：ArrayWeekPoint
        * 计算薄弱点的数量：WeekPointCount
        * */
        ArrayList<String> ArrayBasicScore = new ArrayList<>();
        for(int i=0;i<WeekPointCount;i++){
            String BasicScore = mEntityRdqh.getModelSinglePaperInfo().getModelPaperInfo().getKnowledgeList().get(i).getBasicScore();
            ArrayBasicScore.add(BasicScore);
        }

        ArrayList<String> ArrayAvalidScore = new ArrayList<>();
        for(int i=0;i<WeekPointCount;i++){
            String AvalidScore = mEntityRdqh.getModelSinglePaperInfo().getModelPaperInfo().getKnowledgeList().get(i).getAvalidScore();
            ArrayAvalidScore.add(AvalidScore);
        }


        final ArrayList<String> ArrayWeekPoint = new ArrayList<>();
        for(int i=0;i<WeekPointCount;i++){
            String KnowledgeName = mEntityRdqh.getModelSinglePaperInfo().getModelPaperInfo().getKnowledgeList().get(i).getKnowledgeName();
            ArrayWeekPoint.add(KnowledgeName);
        }
        mTvWeekPoint.setText(String.valueOf(WeekPointCount));

        /*
        * 计算考点的数量：TestPointCount
        * */
        int TestPointCount = CommonlyTestPointCount+WeekPointCount;
        mTvTestPoint.setText(String.valueOf(TestPointCount));

        initData(CommonlyTestPointCount,ArrayCommonlyTestPoint,WeekPointCount,ArrayWeekPoint,ArrayBasicScore,ArrayAvalidScore);

        adapter = new ExpandableAdapter();
        mELvTestPoint.setAdapter(adapter);
        mELvTestPoint.setCacheColorHint(0); //防止拖动时出现黑色背景
        mELvTestPoint.setGroupIndicator(null);//设置自带的箭头消失
        mELvTestPoint.setDivider(null);//设置没有分割线
        //遍历所有group,将所有项设置成默认展开
        int groupCount = mELvTestPoint.getCount();
        for (int i=0; i<groupCount; i++) {

            mELvTestPoint.expandGroup(i);

        };

        mELvTestPoint.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {

            @Override
            public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) {
//                ToastUtils.showShort("点击了"+"===groupPosition=="+groupPosition+"===childPosition=="+groupPosition+"==id=="+id);
                return false;
            }
        });

        final List<String> finalArrayCommonlyTestPoint = ArrayCommonlyTestPoint;
        mELvTestPoint.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {

            @Override
            public boolean onChildClick(ExpandableListView parent, View v,
                                        int groupPosition, int childPosition, long id) {
//                ToastUtils.showShort("点击了"+"===groupPosition=="+groupPosition+"===childPosition=="+childPosition+"==id=="+id);
                if(groupPosition==0) {
                    DictionaryActicity.startWithContent(getHolderActivity(), ArrayWeekPoint.get(childPosition));
                }else if(groupPosition==1){
                    DictionaryActicity.startWithContent(getHolderActivity(), finalArrayCommonlyTestPoint.get(childPosition));
                }
                return false;
            }
        });


        int AnswerState = mEntityRdqh.getModelSinglePaperInfo().getModelPaperInfo().getAnswerState();
        if(AnswerState==3){
            mSbtnIntoReview.setText("查看详情");
        }else if(AnswerState==2){
            mSbtnIntoReview.setText("进入自评");
        }else if(AnswerState==1){
            mSbtnIntoReview.setText("继续作答");
        }else if(AnswerState==0){
            mSbtnIntoReview.setText("开始学习");
        }

    }

    private void initData(int CommonlyTestPointCount,List<String> ArrayCommonlyTestPoint,int WeekPointCount,
                          ArrayList<String> ArrayWeekPoint, ArrayList<String> ArrayBasicScore,ArrayList<String> ArrayAvalidScore) {
        //添加父布局数据
        group.add("薄弱点");
        group.add("一般考点");
        //添加子布局数据
        for(int j=0;j<2;j++){
            List<String> childitem=new ArrayList<String>();
            if(j==0){
                for (int i = 0; i < WeekPointCount; i++) {
                    childitem.add(ArrayWeekPoint.get(i)+"<P>"+
                            "得分："+ArrayBasicScore.get(i)+
                            "(该考点达标得分"+ArrayAvalidScore.get(i)+")");
                }
            }else if(j==1) {
                for (int i = 0; i < CommonlyTestPointCount; i++) {
                    childitem.add(ArrayCommonlyTestPoint.get(i));
                }
            }
            child.add(childitem);
        }
    }


    @Override
    public void loadComplete(boolean hasComplete) {

    }

    @Override
    public void openExamReportDialog() {

    }

    @Override
    public void openAssessDialog() {

    }

    @Override
    public void updatingResult(boolean isSucceed) {

    }

    @Override
    public void updatingReportResult(boolean isReportSucceed) {

    }

    @Override
    public LoadingDialog getLoadingDialog() {
        return null;
    }


    class ExpandableAdapter extends BaseExpandableListAdapter {

        @Override
        public int getGroupCount() {
            return group.size();//获取父布局个数
        }

        @Override
        public int getChildrenCount(int groupPosition) {
            return child.get(groupPosition).size();//获取子布局个数
        }

        @Override
        public Object getGroup(int groupPosition) {
            return group.get(groupPosition);
        }

        @Override
        public Object getChild(int groupPosition, int childPosition) {
            return child.get(groupPosition).get(childPosition);
        }

        @Override
        public long getGroupId(int groupPosition) {
            return groupPosition;
        }

        @Override
        public long getChildId(int groupPosition, int childPosition) {
            return childPosition;
        }

        @Override
        public boolean hasStableIds() {
            return true;
        }
        //父布局样式
        @Override
        public View getGroupView(int groupPosition, boolean isExpanded,
                                 View convertView, ViewGroup parent) {
            if(convertView==null){
                LayoutInflater inflater=(LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                convertView=inflater.inflate(R.layout.znbk_elv_item, null);
            }

            View mViewParentVertical = (View) convertView.findViewById(R.id.view_parentVertical);

            TextView mTvParent=(TextView) convertView.findViewById(R.id.tv_parent);
            mTvParent.setText(getGroup(groupPosition).toString());
            ImageView mIvParentCircle=(ImageView) convertView.findViewById(R.id.iv_parentCircle);
            if(groupPosition==0){
                mTvParent.setTextColor(getResources().getColor(R.color.red));
                mIvParentCircle.setBackgroundResource(R.drawable.znbk_red_circle);
            }else if(groupPosition==1){
                mTvParent.setTextColor(getResources().getColor(R.color.blue));
                mIvParentCircle.setBackgroundResource(R.drawable.znbk_blue_circle);
            }

            if(isExpanded){
                Drawable drawableDown = getResources().getDrawable(R.mipmap.znbk_icon_arrow_down);
                drawableDown.setBounds(0,0,drawableDown.getMinimumHeight(),drawableDown.getMinimumHeight());
                mTvParent.setCompoundDrawables(null,null,drawableDown,null);

                mViewParentVertical.setVisibility(View.VISIBLE);
            }else{
                Drawable drawableUp = getResources().getDrawable(R.mipmap.znbk_icon_arrow_up);
                drawableUp.setBounds(0,0,drawableUp.getMinimumHeight(),drawableUp.getMinimumHeight());
                mTvParent.setCompoundDrawables(null,null,drawableUp,null);

                mViewParentVertical.setVisibility(View.GONE);
            }

            return convertView;
        }
        //子布局样式
        @Override
        public View getChildView(int groupPosition, int childPosition,
                                 boolean isLastChild, View convertView, ViewGroup parent) {
            if(convertView==null){
                LayoutInflater inflater=(LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                convertView=inflater.inflate(R.layout.znbk_elv_child, null);
            }
            TextView mTvchild=(TextView) convertView.findViewById(R.id.tv_child);
            mTvchild.setText(Html.fromHtml(getChild(groupPosition, childPosition).toString()));
            ImageView mIvChildCircle=(ImageView) convertView.findViewById(R.id.iv_childCircle);
            if(groupPosition==0){
                mTvchild.setTextColor(getResources().getColor(R.color.red));
                mIvChildCircle.setBackgroundResource(R.drawable.znbk_red_circle);
            }else if(groupPosition==1){
                mTvchild.setTextColor(getResources().getColor(R.color.blue));
                mIvChildCircle.setBackgroundResource(R.drawable.znbk_blue_circle);
            }

            return convertView;
        }

        @Override
        public boolean isChildSelectable(int groupPosition, int childPosition) {
            return true;
        }

    }


}
